package com.quantstack.llhttplibrary;

import android.text.TextUtils;
import android.util.Log;

import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.Logger;

import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author wu_ming_zhi_bei
 * @date 2021/2/9 10:10
 * @Notes
    Describe: Retrofit网络请求工具类,用于初始化Retrofit，设置请求API的baseUrl、gson解析方式
 */
public class EasyHttp {
    private static final int DEFAULT_TIME_OUT = 60;//超时时间 5s
    private static final int DEFAULT_READ_TIME_OUT = 60;
    private Retrofit mRetrofit;
    private static EasyHttp instance;
    private static EasyHttpConfig easyHttpConfig;

    private EasyHttp(){
        // 创建 OKHttpClient
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        //builder.sslSocketFactory(createSSLSocketFactory());
        builder.sslSocketFactory(createSSLSocketFactory(), new TrustAllCerts());
        builder.hostnameVerifier(new TrustAllHostnameVerifier());
        builder.connectTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS);//连接超时时间        builder.writeTimeout(DEFAULT_READ_TIME_OUT,TimeUnit.SECONDS);//写操作 超时时间
        builder.readTimeout(DEFAULT_READ_TIME_OUT,TimeUnit.SECONDS);//读操作超时时间
        // 添加公共参数拦截器
        HttpCommonInterceptor.Builder interceptorBuilder = new HttpCommonInterceptor.Builder();
        if(easyHttpConfig!=null){
            Map<String, String> headers = easyHttpConfig.addHeaders();
            //添加请求头
            if(headers!=null&&headers.size()>0){
                for(Map.Entry<String,String> params:headers.entrySet()){
                    interceptorBuilder.addHeaderParams(params.getKey(),params.getValue());
                }
            }
            //添加参数
            Map<String, String> params = easyHttpConfig.addParams();
            if(params!=null&&params.size()>0){
                for(Map.Entry<String,String> param:params.entrySet()){
                    interceptorBuilder.addGetParams(param.getKey(),param.getValue());
                }
            }
            //添加拦截器
            builder.addInterceptor(interceptorBuilder.build());

            Set<Interceptor> interceptors = easyHttpConfig.addInterceptor();
            if(interceptors!=null&&interceptors.size()>0){
                for(Interceptor interceptor:interceptors){
                    builder.addInterceptor(interceptor);
                }
            }
        }

        HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.i(EasyHttp.class.getName(),message);
            }
        });
        //包含header、body数据
        logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        builder.addNetworkInterceptor(logInterceptor);
        // 创建Retrofit
        mRetrofit = new Retrofit.Builder()
                .client(builder.build())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(easyHttpConfig.baseUrl())
                .build();
    }

    public static EasyHttp getInstance(){
        if(instance==null){
            synchronized (EasyHttp.class){
                if(instance==null){
                    instance = new EasyHttp();
                }
            }
        }
        return instance;
    }

    /**
     * 初始化
     * @param config
     */
    public static void init(EasyHttpConfig config){
        //初始化日志
        Logger.addLogAdapter(new AndroidLogAdapter());
        if(config==null){
            throw new RuntimeException("网络请求配置不可为空");
        }else if(TextUtils.isEmpty(config.baseUrl())){
            throw new RuntimeException("网络请求地址不可为空");
        }
        easyHttpConfig = config;
    }


    /**
     * 获取对应的Service
     * @param service Service 的 class
     * @param <T>
     * @return
     */
    public <T> T create(Class<T> service){
        return mRetrofit.create(service);
    }

    /**
     * 获取mRetrofit实例
     */
    public Retrofit getRetrofit(String baseUrl){
        if(mRetrofit!=null){
            return mRetrofit;
        }else{
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            return retrofit;
        }
    }

    private static class TrustAllCerts implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }

    private static class TrustAllHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    private static SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory ssfFactory = null;
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new TrustAllCerts()}, new SecureRandom());
            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
        }
        return ssfFactory;
    }
}
